package com.golxen.framework.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException;

import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;

@SuppressWarnings({ "deprecation", "rawtypes", "unchecked" })
public class JedisPoolUtils extends JedisPool {
	/** 连接redis失败的次数 */
	private AtomicInteger poolFailCount;

	public JedisPoolUtils(final GenericObjectPoolConfig poolConfig, final String host, int port, int timeout,
			final String password,int database) {
		super(poolConfig, host, port, timeout, password,database);
		poolFailCount = new AtomicInteger(0);
	}

	@Override
	public Jedis getResource() {
		Jedis jedis = null;
		try {
			jedis = internalPool.borrowObject();
		} catch (NoSuchElementException nse) {
			throw new JedisException("Could not get a resource from the pool", nse);
		} catch (Exception e) {
			poolFailCount.incrementAndGet();
			throw new JedisConnectionException("Could not get a resource from the pool", e);
		}
		if (jedis == null)
			jedis = super.getResource();
		else
			jedis.setDataSource(this);

		poolFailCount.set(0);
		return jedis;
	}

	public int getPoolFailCount() {
		return poolFailCount.get();
	}
}
